<template>
    <div class="div-1">
        <div>
            <el-row style="height:100%;">
                <el-col :span="6" style="padding: 10px;">
                    <div style="display: flex; flex-direction: column;">
                        <el-select v-model="data.databaseId" clearable placeholder="请选择数据源" style="margin-bottom: 10px;"
                            @change="databaseChange">
                            <el-option v-for="item in data.dataList" :key="item.id" :label="item.name"
                                :value="item.id" />
                        </el-select>
                        <el-select v-model="data.tableId" @change="masterTable"  clearable placeholder="请选择数据表" style="margin-bottom: 10px;">
                            <el-option v-for="o in data.value" :key="o" :label="data.data[o]['label']"
                                :value="o" />
                        </el-select>
                        <el-upload class="upload-demo" drag multiple :limit="1" :on-change="handleFileChange">
                            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                            <div class="el-upload__tip text-red">
                                仅支持csv/sql/xls/xlsx文件格式
                            </div>
                        </el-upload>
                        <div style="display: flex;margin-bottom: 10px;">
                            <text style="text-align: center;width: 60px;padding: 5px 12px 6px 12px;background-color:#f5f7fa;border: 1px solid #dcdfe6; color: #909399;
                            font-size: 14px;border-radius: 5px 0 0 5px;border-right-width: 0px;">起始行</text>
                            <el-input-number controls-position="right" v-model="data.start" :min="1" :max="30"
                                style="width: 100%;border-top-left-radius: 0px;border-bottom-left-radius: 0px;"
                                @change="handleChange"></el-input-number>
                        </div>
                        <el-button type="primary" @click="filePath"  style="width: 100%;margin-bottom: 10px;">开始插入信息</el-button>
                        <el-button type="primary" @click="file" style="width: 100%;margin-left: 0;">
                            测试导入数据
                        </el-button>
                    </div>

                </el-col>
                <el-col :span="18">
                    <div class="dataUrl" v-if="data.tableTF">
                        <el-transfer v-model="data.value" :data="data.data" style="margin: 0 auto;"
                            :titles="['数据库表', '已选择表']" />
                        <el-button class="dataUrl" type="primary" @click="data.tableTF = !data.tableTF"
                            style="width: 100px;margin: auto;margin-top: 20xp;">
                            完成
                        </el-button>
                    </div>
                    <div v-if="!data.tableTF">
                        <el-table :data="data.fieldInfo" style="height:550px">
                            <el-table-column label="对应列" min-width="200">
                                <template #default="scope">
                                    <el-input-number v-model="scope.row.Column" :min="1" :max="10"
                                        @change="handleChange" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="Field" label="名" min-width="200"/>
                            <el-table-column prop="Comment" label="注释" min-width="200"/>
                            <el-table-column prop="Type" label="类型" min-width="200"/>
                            <el-table-column prop="Null" label="不是空" min-width="200"/>
                            <el-table-column label="是否启用" min-width="120" fixed="right" >
                                <template #default="scope">
                                    <el-switch v-model="scope.row.Enable" inline-prompt active-text="是"
                                        inactive-text="否" />
                                </template>
                            </el-table-column>
                            <el-table-column label="功能" min-width="120" fixed="right" >
                                <template #default="scope">
                                    <el-button link type="primary" size="small"
                                        @click.prevent="deleteRow(scope.$index)">
                                        关联表
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-button class="dataUrl" type="primary" @click="masterField()"
                            style="width: 100px;margin: auto;">
                            完成
                        </el-button>
                    </div>
                </el-col>
            </el-row>
            <div>
                {{ data.sql }}
            </div>
        </div>
        <el-drawer v-model="data.fieldInfoDialog" :with-header="false" size="50%" @close="close" @closed="close">
            <div style="margin: 10px;">
                表：<el-select v-model="data.relateTable" placeholder="Select" style="margin-left: 10px;width: 240px"
                    @change="handleRelateTable">
                    <el-option v-for="(item, index) in data.data" :key="index" :label="item.label" :value="index" />
                </el-select>
            </div>
            <div style="margin: 10px;">
                键：<el-select v-model="data.relateKey" placeholder="Select" style="margin-left: 10px;width: 240px"
                    @change="handleRelateKey">
                    <el-option v-for="item in data.children" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </div>
            <div style="margin: 10px;">
                值：<el-select v-model="data.relateValue" placeholder="Select" style="margin-left: 10px;width: 240px"
                    @change="handleRelateValue">
                    <el-option v-for="item in data.children" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </div>
            <el-button class="dataUrl" type="primary" @click="masterRelate" style="width: 100px;margin: auto;">
                完成
            </el-button>
        </el-drawer>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { FileHandler, GetConfig, Metadata, SaveFile } from '../../wailsjs/go/main/App'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx';
const data = reactive({
    // 数据库连接字符串
    dataUrl: "MFP:MFP@(127.0.0.1:3306)/mfp?charset=utf8mb4&parseTime=True&loc=Local",
    // 数据库连接结果
    result: {},
    value: [],
    data: [],
    tableTF: true,
    sql: "",
    masterTableTF: false,
    ETF: true,
    DTF: false,
    fieldInfo: [],
    fieldInfoIndex: 0,
    fieldInfoDialog: false,
    selectField: [],
    table: "",
    children: [],
    relateTable: "",
    relateIndex: 0,
    relateKey: "",
    relateValue: "",
    path: "D:\\Users\\Desktop\\新建 XLS 工作表.xlsx",
    start: 1,
    uploadFile: false,
    dataList: [],
    databaseId: undefined,
})

const file2 = ref(null);

const handleFileChange = (uploadFile) => {
    //   file2.value = uploadFile.raw
    //   const reader = new FileReader()
    //   reader.readAsArrayBuffer(file2.value)
    //   reader.onload = async () => {
    //     const buffer = new Uint8Array(reader.result)
    //     SaveFile(file2.value.name, Array.from(buffer))
    //   }
    readXlsByChunks(uploadFile.raw)
}

async function readXlsByChunks(file, chunkSize = 20) {

    const reader = new FileReader();
    const workbook = await new Promise(resolve => {
        reader.onload = (e) => {
            resolve(XLSX.read(e.target.result, { type: 'array' }));
        };
        reader.readAsArrayBuffer(file);
    });

    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    const range = XLSX.utils.decode_range(sheet['!ref']);
    let buffer = [];

    for (let rowNum = range.s.r; rowNum <= range.e.r; rowNum++) {
        const row = [];
        for (let colNum = range.s.c; colNum <= range.e.c; colNum++) {
            const cell = sheet[XLSX.utils.encode_cell({ r: rowNum, c: colNum })];
            row.push(cell ? cell.v : '');
        }
        buffer.push(row);
        if (buffer.length >= chunkSize) {
            processChunk(file.name, buffer);
            buffer = [];
        }
    }

    if (buffer.length > 0) {
        processChunk(file.name, buffer);
    }
}

function processChunk(name, rows) {
    SaveFile(name, rows)
    console.log('处理批数据:', rows);
    // 这里添加分块处理逻辑，例如：
    // await fetch('/api/upload', {
    //   method: 'POST',
    //   body: JSON.stringify(rows)
    // });
}


function getList() {
    GetConfig().then(result => {
        data.dataList = result
    })
}

function databaseChange(val) {
    if (val != undefined) {
        Metadata(val).then(result => {
            data.result = result
            data.data = result.data
            if (result.code != 200) {
                ElMessage({
                    showClose: true,
                    message: result.msg,
                    type: 'error',
                })
            }
        }).catch(err => {
            console.log(err)
        })

    }
}

function masterTable(e) {
    data.table = data.data[e]["table"]
    data.masterTableTF = true;
    data.fieldInfo = data.data[e]["fieldInfo"]
}

function masterField() {
    data.sql = ""
    for (let i = 0; i < data.fieldInfo.length; i++) {
        if (data.fieldInfo[i].Enable) {
            if (data.fieldInfo[i].Column == null || data.fieldInfo[i].Column == undefined || data.fieldInfo[i].Column == "") {
                ElMessage.error('对应列不能为空')
                return
            }
            var v = ""
            if (data.fieldInfo[i].relateKey != null) {
                v = "[Table=" + data.fieldInfo[i].relateTable + ",Key=" + data.fieldInfo[i].relateKey +
                    ",Value=" + data.fieldInfo[i].relateValue + ",Column=" + data.fieldInfo[i].Column + "]"
            }
            if (data.sql != "") {
                data.sql = data.sql + "," + data.fieldInfo[i]["Field"] + v

            } else {
                data.sql = data.fieldInfo[i]["Field"] + v
            }
        }
    }
    if (data.sql != "") {
        data.sql = "insert into " + data.table + " (" + data.sql + ")"
    } else {
        ElMessage.error('请选择字段')
    }

}

function deleteRow(index) {
    data.fieldInfoIndex = index;
    if (data.fieldInfo[data.fieldInfoIndex].relateTable != "") {
        data.relateTable = data.fieldInfo[data.fieldInfoIndex].relateTable
        data.relateKey = data.fieldInfo[data.fieldInfoIndex].relateKey
        data.relateValue = data.fieldInfo[data.fieldInfoIndex].relateValue
    }
    data.fieldInfoDialog = true;
}

function handleRelateTable(value) {
    data.relateIndex = value
    data.relateTable = data.data[value]["table"]
    data.children = data.data[value].fieldInfo
    data.relateKey = ""
    data.relateValue = ""
}

function masterRelate() {
    data.fieldInfo[data.fieldInfoIndex].relateTable = data.relateTable
    data.fieldInfo[data.fieldInfoIndex].relateKey = data.relateKey
    data.fieldInfo[data.fieldInfoIndex].relateValue = data.relateValue
    close()
}

function close() {
    data.relateTable = "";
    data.relateKey = "";
    data.relateValue = "";
    data.fieldInfoDialog = false;
}

function handleRelateKey(value) {
    data.fieldInfo[data.fieldInfoIndex].relateKey = value
}

function handleRelateValue(value) {
    data.fieldInfo[data.fieldInfoIndex].relateValue = value
}

function filePath() {
    if (data.path != "") {
        var fieldInfoData = []
        for (let i = 0; i < data.fieldInfo.length; i++) {
            if (data.fieldInfo[i].Enable) {
                fieldInfoData.push(data.fieldInfo[i])
            }
        }
        FileHandler(data.table, data.path, fieldInfoData, data.start).then(result => {
            ElMessage.info(result["data"] + result["msg"])
        }).catch(err => {
            console.log(err)
        })
    } else {
        ElMessage.error('文件地址不能为空')
    }
}

function file() {
    FileHandler("D:\\Users\\Desktop\\新建 XLS 工作表")
}

onMounted(async () => {
    getList();
});

</script>

<style>
.el-transfer-panel{
    width: 300px;
}
.div-1 {
    text-align: left;
    padding: 20px;
    display: flex;
    flex-direction: column;
}

.dataUrl {

    margin-top: 10PX;
    display: flex;
    flex-direction: column;
}

.dataUrl-input {
    min-width: 240px;
    margin: 10px 0;
}
</style>
